# coding:  utf-8
import random
import requests
import time

class RequestUtils(object):
    
    
    def __init__(self, cookie=None, token=None):
        '''
        cookie: str
        token: str
            登陆微信公众号获取
        '''
        self.s = requests.session()
        self.headers = {
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
        }
        self.params = {
            "lang": "zh_CN",
            "f": "json",
        }
        self.count = 0
        #验证cookie和token
        if (cookie != None and token != None):
            self.headers["Cookie"] = cookie
            self.params["token"] = token
        else:
            print("please check your profile")
            raise SystemError
    
    
    def subscription_info(self, nickname, begin=0, count=5):
        """
        获取公众号的一些信息
        Parameters
        ----------
        nickname: str
            公众号名称
        begin: str or int
            起始爬取的页数
        count: str or int
            每次爬取的数量，1-5

        Returns
        -------
        json:
            公众号的一些信息
            {
              'fakeid': 公众号唯一id,
              'nickname': 公众号名称,
              'alias': 公众号别名,
              'round_head_img': 公众号头像的url,
              'service_type': 1公众号性质
            }
        """
        # 搜索公众号的url
        search_url = "https://mp.weixin.qq.com/cgi-bin/searchbiz"

        # 增加/更改请求参数
        params = {
            "action": "search_biz",
            "ajax": "1",
            "random":str(random.uniform(0, 1)),
            "query": nickname,
            "begin": str(begin),
            "count": str(count)
        }
        params.update(self.params)

        try:
            # 返回输入公众号名称搜索结果的第一个公众号信息
            subscription = self.s.get(
                search_url, headers=self.headers, params=params)
            return subscription.json()["list"][0]
        except Exception:
            raise Exception(u"公众号名称错误或cookie、token错误，请重新输入")
    
        
    def articles_nums(self, fakeid):
        '''
        获取公众号的总文章数
        nickname: str
            公众号名称
        '''
        try:
            return self.get_articles_data(fakeid, begin="0")["app_msg_cnt"]
        except Exception:
            raise Exception(u"公众号名称错误或cookie、token错误，请重新输入")
    
        
    def getDate(self, appmsg_url, headers, params):
        try:
            data = self.s.get(appmsg_url, headers=headers, params=params)
            self.count = 0
        except Exception:
            if self.count > 5:
                raise Exception(u"网络异常！！！")
            self.count += 1
            time.sleep(3)
            return self.getDate(appmsg_url = appmsg_url, headers = headers, params = params)
        return data.json()
    
    def get_articles_data(self,
                            fakeid,
                            begin,
                            count=5,
                            type_='9',
                            action='list_ex',
                            query=None):
        '''
        获取公众号信息
        Parameters
        ----------
        fakeid: str
            爬取公众号的id
        begin: str or int
            爬取的当前页数
        count: str or int
            每次爬取的文章数，默认5
        type_: str or int
            获取数据的方式，默认9
        action: str
            请求之后的行为动作，"list_ex"获取文章信息的json
        Returns
        -------
        json:
            文章信息的json
            {
              'app_msg_cnt': 公众号发文章总数,
              'app_msg_list': 　文章列表数组,
              'base_resp': {
                'err_msg': 'ok',
                'ret': 0
              }
            }    
        
        '''
        # 获取文章信息的url
        appmsg_url = "https://mp.weixin.qq.com/cgi-bin/appmsg"

        # 增加/更改请求参数
        params = {
            "fakeid": str(fakeid),
            "ajax": "1",
            "random": str(random.uniform(0, 1)),
            "action": action,
            "begin": str(begin),
            "count": str(count),
            "query": query if query != None else "",
            "type": str(type_)
        }
        params.update(self.params)
        
        return self.getDate(appmsg_url = appmsg_url, headers = self.headers, params = params)
